package com.ffcs.web.services;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffcs.web.controllers.AdvertController;
import com.ffcs.web.daos.implementations.AuthCodeDao;
import com.ffcs.web.model.entity.AuthCode;

@Service
public class AuthCodeService {

	private Logger logger = Logger.getLogger(AuthCodeService.class);
	
	@Autowired
	private AuthCodeDao authCodeDao;

	@Transactional
	public String save(String telphone, String code) {
		
		//清空该号码之前的验证码数据
		List<AuthCode> authCodeList = authCodeDao.findByPropertyName("telphone", telphone);
		if(authCodeList.size()>0){
			AuthCode authCode=authCodeList.get(0);
			authCode.setAuthCode(code);
			authCode.setTelphone(telphone);
			authCode.setStartTime(new Date());
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			//加5分钟
			calendar.add(Calendar.MINUTE, +5);
			Date date=calendar.getTime();			
			authCode.setEndTime(date);
			authCodeDao.save(authCode);
			logger.info("[code="+code+"]更新验证码到数据库成功");
			return code;
		}else{
			AuthCode authCode=new AuthCode();
			authCode.setAuthCode(code);
			authCode.setTelphone(telphone);
			authCode.setStartTime(new Date());
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			//加5分钟
			calendar.add(Calendar.MINUTE, +5);
			Date date=calendar.getTime();			
			authCode.setEndTime(date);
			authCodeDao.save(authCode);
			logger.info("[code="+code+"]保存验证码到数据库成功");
			return code;
		}
	}

	/**
	 * 校验验证码
	 * @param code
	 * @return
	 */
	public boolean isAuthCode(String telphone,String code) {
		AuthCode authCode=new AuthCode();
		authCode.setAuthCode(code);
		authCode.setTelphone(telphone);
		List<AuthCode> esmAuthCodeList = authCodeDao.findByExample(authCode);
		if(esmAuthCodeList.size()==1){
			
			AuthCode ec=esmAuthCodeList.get(0);
			
			if(ec.getEndTime().getTime()>new Date().getTime()){
				logger.error("[authCode="+code+"]验证码未失效");
				return true;
			}else{
				logger.error("[authCode="+code+"]验证码已失效");
				return false;
			}
		}
		logger.error("[authCode="+code+"]验证码不存在");
		return false;
	}
	
}
